import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useUserStore } from './user'
import { insertCartAPI, findNewCartListAPI, delCartAPI } from '@/apis/cart'
export const useCartStore = defineStore(
  'cart',
  () => {
    const updateNewList = async () => {
      const res = await findNewCartListAPI()
      cartList.value = res.result
    }
    // 将购物车变成登录状态下才可访问
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)
    // 1.定义cartList
    const cartList = ref([])
    // 2.定义action-addCart

    const addCart = async (goods) => {
      // 添加购物车
      // 已经添加过-count+1,没有则-直接push
      // 登录判断
      const { skuId, count } = goods
      if (isLogin.value) {
        // 登录之后操作
        await insertCartAPI({ skuId, count })
        const res = await findNewCartListAPI()
        cartList.value = res.result
      } else {
        const item = cartList.value.find((item) => goods.skuId === item.skuId)
        if (item) {
          // 找到了
          item.count++
        } else {
          cartList.value.push(goods)
        }
      }
    }
    // 删除购物车
    const delCart = async (skuId) => {
      if (isLogin.value) {
        delCartAPI([skuId])
        const res = await findNewCartListAPI()
        cartList.value = res.result
      } else {
        const idx = cartList.value.findIndex((item) => skuId === item.skuId)
        cartList.value.splice(idx, 1)
      }
    }
    // 计算属性
    // 1.总数量count之和
    const allCount = computed(() => {
      return cartList.value.reduce((a, c) => a + c.count, 0)
    })
    // 2.总价格count与price之积
    const allPrice = computed(() => {
      return cartList.value.reduce((a, c) => a + c.count * c.price, 0)
    })
    // 购物车模块是否全选
    const isAll = computed(() => cartList.value.every((item) => item.selected))
    // 全选功能
    const allCheck = (selected) => {
      cartList.value.forEach((item) => (item.selected = selected))
    }
    // 购物车列表单选框
    const singleCheck = (skuId, selected) => {
      const item = cartList.value.find((item) => item.skuId === skuId)
      item.selected = selected
    }

    // 清单已选择商品数量和总价
    const selectedCount = computed(() =>
      cartList.value
        .filter((item) => item.selected)
        .reduce((a, c) => a + c.count, 0)
    )
    const selectedPrice = computed(() =>
      cartList.value
        .filter((item) => item.selected)
        .reduce((a, c) => a + c.count * c.price, 0)
    )
    const selectedNum = computed(
      () => cartList.value.filter((item) => item.selected).length
    )

    return {
      cartList,
      addCart,
      delCart,
      allCount,
      allPrice,
      singleCheck,
      isAll,
      allCheck,
      selectedCount,
      selectedPrice,
      selectedNum,
      updateNewList
    }
  },
  {
    persist: true
  }
)
